package com.example.java.kafka.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

public class CustomProducerCallbackMyCustomPartitioner {
    public static void main(String[] args) {
        KafkaProducer<String, String> kafkaProducer = CustomProducerCallbackMyCustomPartitioner.getKafkaProducer();
        for (int i = 0; i < 5; i++) {
            String message = "Kafka" + i;
            kafkaProducer.send(new ProducerRecord<>("producer2", message), (recordMetadata, e) -> {
                if (e == null) {
                    System.out.println("主题:" + recordMetadata.topic() + " -> " + message + " 消息发往分区:" + recordMetadata.partition());
                } else {
                    e.printStackTrace();
                }
            });
        }
        kafkaProducer.close();
    }

    private static KafkaProducer<String, String> getKafkaProducer() {
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "43.139.50.31:9092");
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        // 添加自定义的分区器
        properties.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, MyCustomPartitioner.class.getName());
        return new KafkaProducer<>(properties);
    }
}